# coding: utf-8
import json
import os
import time
import datetime
import random
import requests
import redis
import sys


# TODO 未验证
class XiechengTicket(object):
    def __init__(self):
        self.rd = redis.Redis()
        self.rd2 = redis.Redis(db=1)
        self.rd3 = redis.Redis(db=2)
        self.rediskey = 'xiecheng_airport'
        self.rediskey_err = 'xiecheng_airport_err'
        self.rediskey_time = datetime.datetime.now().strftime('%Y-%m-%d')

        _path = os.path.join(os.path.abspath('.'), '../')
        sys.path.append(_path)
        self.ei = __import__('Utils.C002_extract_info', fromlist=['C002_extract_info'])
        self.ua_file = {'pc': '{0}Utils/{1}'.format(_path, self.ei.ExtractInfo.ua_file['pc'])}
        self.user_agent = self.ei.ExtractInfo.get_useragent(file=self.ua_file)

    def parse_code(self, codes):
        _res_codes = []
        for i in codes:
            for j in codes:
                if i != j:
                    _res_codes.append((i, j))
        return _res_codes

    def parse_data(self, urls, cookies):
        _temp_data = []
        while True:
            for _url in urls:
                cookies['FD_SearchHistorty'] = str(cookies['FD_SearchHistorty'])
                _response = requests.get(_url, headers=self.user_agent, cookies=cookies)
                time.sleep(random.random())

                _lis = _response.json()['fis']
                for _li in _lis:
                    _temp = {}
                    _temp['acc'] = _li['acc']
                    _temp['acn'] = _li['acn']
                    _temp['apbn'] = _li['apbn']
                    _temp['at'] = _li['at']
                    _temp['dcc'] = _li['dcc']
                    _temp['dcn'] = _li['dcn']
                    _temp['dpbn'] = _li['dpbn']
                    _temp['dt'] = _li['dt']
                    _temp['fn'] = _li['fn']
                    _temp['pr'] = _li['pr']
                    _temp['tax'] = _li['tax']
                    _temp['cf'] = {
                        'c': _li['cf']['c'],
                        'dn': _li['cf']['dn'],
                        's': _li['cf']['s']
                    }
                    _conforts = json.loads(_li['confort'])
                    _temp['confort'] = {
                        'dapart_bridge': _conforts['DepartBridge'],
                        'history_punctuality': _conforts['HistoryPunctuality'],
                        'history_punctuality_arr': _conforts['HistoryPunctualityArr']
                    }
                    _scss = _li['scs']
                    _temp_price = []
                    for _scs in _scss:
                        _temp_scs = {}
                        _temp_scs['rt'] = _scs['rt']
                        _temp_scs['salep'] = _scs['salep']
                        _temp_price.append(_temp_scs)
                    _temp['scs'] = _temp_price
                    _temp['time'] = time.ctime()
                    _temp['url'] = _url
                    time.sleep(random.random())

                    if _temp not in _temp_data:
                        _temp_data.append(_temp)
                        self.rd3.rpush(self.rediskey_time, _temp)

    def run(self):
        _datas = self.rd.lrange(self.rediskey, 0, -1)
        _data = json.loads(_datas[0].decode().replace("'{", "{").replace("}'", "}").replace("'", "\""))
        _cookies = _data['cookie']
        _datas = self.rd2.lrange(self.rediskey_err, 0, -1)
        _urls = []
        for _data in _datas:
            _data = json.loads(_data.decode().replace("'", "\""))
            for _url, _error in _data.items():
                _urls.append(_url)
        self.parse_data(_urls, _cookies)


def main():
    xc = XiechengTicket()
    xc.run()


if __name__ == '__main__':
    main()
